package com.hnkywl.sts.service.jsgl;

import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.cggl.CgdmxDao;
import com.hnkywl.sts.dao.jsgl.CgjsdDao;
import com.hnkywl.sts.dao.jsgl.CgjsdmxDao;
import com.hnkywl.sts.dao.jsgl.ZjbcdDao;
import com.hnkywl.sts.entity.cggl.*;
import com.hnkywl.sts.service.base.BmService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.BaseUtils;
import com.hnkywl.sts.util.ReflectionUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-4-23
 * Time: 上午9:09
 * To change this template use File | Settings | File Templates.
 */
@Service
public class CgjsdService {
    private CgjsdDao cgjsdDao;
    private CgjsdmxDao cgjsdmxDao;
    private BmService bmService;
    private CgdmxDao cgdmxDao;
    private CgdDao cgdDao;
    private ZjbcdDao zjbcdDao;

    @Transactional
    public String findAllCgjsd(Integer zt, String jsdh, Date sqrqStart, Date sqrqEnd, Long glqyId, Long gsId, String gsJc, Long fpzlId, int pageNo, int pageSize) {
        if ("".equals(gsJc)) {
            gsId = null;
        }
        Page<Jsd> cgjsdPage = this.cgjsdDao.findCgjsdList(zt, jsdh, sqrqStart, sqrqEnd, glqyId, gsId, gsJc, fpzlId, pageNo, pageSize);
        List<Jsd> cgjsdList = cgjsdPage.getResult() == null ? new ArrayList<Jsd>() : cgjsdPage.getResult();
        String cgjsdJson = BaseUtils.fetchCollectionToJson(cgjsdList, "id", "jsdh", "glqy.qyfr.nsh", "sqrq", "type", "glqy.id", "glqy.qc", "fpze", "ddfy", "fpzl", "hm", "sqr.id",
                "sqr.xm", "gs.id", "gs.jc", "cggs.jc", "cggs.jc", "zt", "bz", "fpthyy", "sftzd");
        return "{\"total\":" + cgjsdPage.getTotalCount() + ",\"rows\":[" + cgjsdJson + "]}";
    }

    /**
     * 首页显示采购结算单
     *
     * @return
     */
    public String findAllCgjsd(Integer zt, Integer type) {
        return this.cgjsdDao.findAllCgjsd(zt, type);
    }


    /**
     * 保存采购单结算
     *
     * @param cgjsd
     */
    @Transactional
    public void saveCgjsd(Jsd cgjsd) throws SQLException {
        cgjsd.setJsdh(bmService.getJsdbm("CGJS"));
        cgjsd.setShzt(0);
        cgjsd.setZt(0);
        cgjsd.setCggs(cgjsd.getGs());
        nullId(cgjsd);
        cgjsd.setSqrq(new Date());
        cgjsd.setType(0); //type=0 采购 ; 1 销售，2物流
        cgjsd.setDateCreated(new Date());
        cgjsd.setLastUpdated(cgjsd.getDateCreated());
        cgjsd.setCreateUser(YgService.getCurrentYg());
        cgjsd.setCreateOrgan(YgService.getCurrentYg().getZggs());
        cgjsd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        this.cgjsdDao.save(cgjsd);

        if (cgjsd.getCgdmxList() != null) {
            for (Cgdmx temp : cgjsd.getCgdmxList()) {
                Cgdmx clone = cgdmxDao.get(temp.getId());
                clone.setJsbhse(temp.getJsbhse());
                clone.setJsse(temp.getJsse());
                clone.setJsce(temp.getJsce());
                java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
                String jsbhsj = "0.0000";
                if (clone.getRksl() != null && clone.getRksl() != 0) {
                    jsbhsj = df.format(temp.getJsbhse() / clone.getRksl());
                }
                clone.setJsbhsj(Double.parseDouble(jsbhsj));
                String jshsj = "0.0000";
                if (clone.getRksl() != null && clone.getRksl() != 0) {
                    jshsj = df.format((temp.getJsbhse() + temp.getJsse()) / clone.getRksl());
                }
                clone.setJshsj(Double.parseDouble(jshsj));
                clone.setDateCreated(new Date());
                clone.setLastUpdated(clone.getLastUpdated());
                clone.setCreateUser(YgService.getCurrentYg());
                clone.setCreateOrgan(YgService.getCurrentYg().getZggs());
                clone.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                clone.setCgjsd(cgjsd);
                cgdmxDao.save(clone);
            }

        }
        if (cgjsd.getZjbcdList() != null) {
            for (Zjbcd zjbcdTemp : cgjsd.getZjbcdList()) {
                Zjbcd zjbcd = this.zjbcdDao.get(zjbcdTemp.getId());
                zjbcd.setGys(cgjsd.getGlqy());
                zjbcd.setZt("ybc");
                zjbcd.setDateCreated(new Date());
                zjbcd.setLastUpdated(zjbcd.getDateCreated());
                zjbcd.setCreateUser(YgService.getCurrentYg());
                zjbcd.setCreateOrgan(YgService.getCurrentYg().getZggs());
                zjbcd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                zjbcdDao.save(zjbcd);
            }
        }
    }


    /**
     * 修改销售单结算
     *
     * @param cgjsd
     */
    @Transactional
    public void updateCgjsd(Jsd cgjsd) {
        Jsd clone = this.findCgjsdDetail(cgjsd.getId());
        cgjsd.setSqrq(clone.getSqrq());
        cgjsd.setZt(clone.getZt());
        cgjsd.setShzt(clone.getShzt());
        // cgjsd.setKprq(clone.getKprq());
        cgjsd.setKpr(clone.getKpr());
        nullId(cgjsd);
        clone = (Jsd) ReflectionUtils.getInstance(clone, cgjsd);
        clone.setLastUpdated(new Date());
        clone.setCggs(clone.getGs());
        this.cgjsdDao.save(clone);
        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
        if (cgjsd.getCgdmxList() != null) {
            for (Cgdmx temp : cgjsd.getCgdmxList()) {
                if (temp.getId() != null) {
                    Cgdmx c = cgdmxDao.get(temp.getId());
                    c.setJsbhse(temp.getJsbhse());
                    c.setJsse(temp.getJsse());
                    c.setJsce(temp.getJsce());
                    String jsbhsjstr = "0.0000";
                    if (c.getRksl() != null & c.getRksl() != 0) {
                        jsbhsjstr = df.format(temp.getJsbhse() / c.getRksl());
                    }
                    c.setJsbhsj(Double.valueOf(jsbhsjstr));
                    String jshsjstr = "0.0000";
                    if (c.getRksl() != null & c.getRksl() != 0) {
                        jshsjstr = df.format((temp.getJsbhse() + temp.getJsse()) / c.getRksl());
                    }
                    c.setJshsj(Double.valueOf(jshsjstr));
                    c.setLastUpdated(new Date());
                } else {
                    temp.setJsbhse(temp.getJsbhse());
                    temp.setJsse(temp.getJsse());
                    temp.setJsce(temp.getJsce());
                    String jsbhsjstr = "0.0000";
                    if (temp.getRksl() != null && temp.getRksl() != 0) {
                        jsbhsjstr = df.format(temp.getJsbhse() / temp.getRksl());
                    }
                    temp.setJsbhsj(Double.valueOf(jsbhsjstr));
                    String jshsjstr = "0.0000";
                    if (temp.getRksl() != null && temp.getRksl() != 0) {
                        jshsjstr = df.format((temp.getJsbhse() + temp.getJsse()) / temp.getRksl());
                    }
                    temp.setJshsj(Double.valueOf(jshsjstr));
                    temp.setDateCreated(new Date());
                    temp.setLastUpdated(temp.getDateCreated());
                    temp.setCreateUser(YgService.getCurrentYg());
                    temp.setCreateOrgan(YgService.getCurrentYg().getZggs());
                    temp.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                }
            }
        }

        if (cgjsd.getZjbcdList() != null) {
            for (Zjbcd zjbcdTemp : cgjsd.getZjbcdList()) {
                if (zjbcdTemp.getId() != null) {
                    Zjbcd zjbcd = this.zjbcdDao.get(zjbcdTemp.getId());
                    zjbcd.setLastUpdated(new Date());
                } else {
                    zjbcdTemp.setGys(cgjsd.getGlqy());
                    zjbcdTemp.setZt("ybc");
                    zjbcdTemp.setDateCreated(new Date());
                    zjbcdTemp.setLastUpdated(zjbcdTemp.getDateCreated());
                    zjbcdTemp.setCreateUser(YgService.getCurrentYg());
                    zjbcdTemp.setCreateOrgan(YgService.getCurrentYg().getZggs());
                    zjbcdTemp.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                }
            }
        }
    }

    /**
     * 删除销售单结算
     *
     * @param id
     */
    @Transactional
    public void deleteCgjsd(Long id) {
        Jsd cgjsd = this.findCgjsdDetail(id);
        cgjsd.setLastUpdated(new Date());
        cgjsd.setDeleted(1);
        this.cgjsdDao.save(cgjsd);
        if (cgjsd.getCgdList() != null) {
            for (Cgd c : cgjsd.getCgdList()) {
                Cgd newInstance = cgdDao.findUniqueByProperty("id", c.getId());
                newInstance.setYjs(false);
                newInstance.setCgjsd(null);
                newInstance.setLastUpdated(new Date());
                if ("bght".equals(newInstance.getCglx())) {
                    String sql = "insert into t_biz_cgd_wg (id,cgd_id,zt,flag,date_created,last_updated) values (seq_biz_cgd_wg.nextval,?,?,?,?,?)";
                    cgdDao.executeSQL(sql, newInstance.getId(), 6, 1, new Date(), new Date());
                }
            }
        }
        if (cgjsd.getCgdmxList() != null) {
            for (Cgdmx c : cgjsd.getCgdmxList()) {
                Cgdmx newInstance = cgdmxDao.findUniqueByProperty("id", c.getId());
                newInstance.setYjs(false);
                newInstance.setCgjsd(null);
                newInstance.setLastUpdated(new Date());
            }
        }
    }

    /**
     * 查询收款审核明细
     *
     * @param id
     * @return
     */
    @Transactional
    public Jsd findCgjsdDetail(Long id) {
        return this.cgjsdDao.get(id);
    }


    /**
     * 审核状态
     *
     * @param id
     * @param status
     */
    @Transactional
    public void changeStatus(Long id, Integer status) {
        Jsd cgjsd = this.findCgjsdDetail(id);
        cgjsd.setZt(status);
        cgjsd.setShzt(0);
        cgjsd.setLastUpdated(new Date());
        Map<Long, Cgd> map = new HashMap<Long, Cgd>();
        for (Cgdmx x : cgjsd.getCgdmxList()) {
            x.setYjs(true);
            x.setLastUpdated(new Date());
            if (map.get(x.getCgd().getId()) == null)
                map.put(x.getCgd().getId(), x.getCgd());
        }
        this.cgjsdDao.save(cgjsd);
        for (Long cgdId : map.keySet()) {
            Cgd cgd = map.get(cgdId);
            List<Cgdmx> cgdmxes = cgd.getCgdmxList();
            Boolean flag = true;
            for (Cgdmx cgdmx : cgdmxes) {
                if (cgdmx.getYjs() == null || !cgdmx.getYjs()) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                cgd.setYjs(true);
                this.cgdDao.save(cgd);
                if ("bght".equals(cgd.getCglx())) {
                    String sql = "insert into t_biz_cgd_wg (id,cgd_id,zt,flag,date_created,last_updated) values (seq_biz_cgd_wg.nextval,?,?,?,?,?)";
                    cgdDao.executeSQL(sql, cgd.getId(), 5, 1, new Date(), new Date());
                }
            }
        }
        // 保存采购单结算单单明细，先删除再保存
        List<Cgjsdmx> cgjsdmxList =  cgjsd.getCgjsdmxList();
        if(null != cgjsdmxList && cgjsdmxList.size() > 0 ){
            for(Cgjsdmx cgjsdmx : cgjsdmxList){
                cgjsdmx.setLastUpdated(new Date());
                cgjsdmx.setDeleted(1);
                this.cgjsdmxDao.save(cgjsdmx);
            }
        }
        List<Cgdmx> cgdmxList = cgjsd.getCgdmxList();
        for (Cgdmx cgdmx : cgdmxList) {
            Cgjsdmx cgjsdmx = new Cgjsdmx();
            cgjsdmx.setGg(cgdmx.getGg());
            cgjsdmx.setCd(cgdmx.getCd());
            cgjsdmx.setTh(cgdmx.getTh());
            cgjsdmx.setCk(cgdmx.getCk());
            cgjsdmx.setBhsj(cgdmx.getBhsj());
            cgjsdmx.setHsj(cgdmx.getHsj());
            cgjsdmx.setRksl(cgdmx.getRksl());
            cgjsdmx.setJe(cgdmx.getJsbhse());
            cgjsdmx.setSe(cgdmx.getJsse());
            cgjsdmx.setCe(cgdmx.getJsce());
            cgjsdmx.setJsd(cgjsd);
            cgjsdmx.setCgdmx(cgdmx);
            cgjsdmx.setCgd(cgdmx.getCgd());
            cgjsdmx.setCreateUser(YgService.getCurrentYg());
            cgjsdmx.setCreateOrgan(YgService.getCurrentYg().getZggs());
            cgjsdmx.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            cgjsdmx.setDateCreated(new Date());
            cgjsdmx.setLastUpdated(cgjsdmx.getDateCreated());
            this.cgjsdmxDao.save(cgjsdmx);
        }
    }

    /**
     * 采购结算单冲销
     *
     * @param ycgjsd
     */
    @Transactional
    public void cgjsdtz(Jsd ycgjsd) {
        Jsd hccgjsd = new Jsd();
        ReflectionUtils.getInstance(hccgjsd, ycgjsd);
        nullId(hccgjsd);
        hccgjsd.setId(null);
        hccgjsd.setJsdh(bmService.getJsdbm("CGJS"));
        if (hccgjsd.getDdfy() != null)
            hccgjsd.setDdfy(0 - hccgjsd.getDdfy());
        hccgjsd.setMe(0 - hccgjsd.getMe());
        hccgjsd.setJe(0 - hccgjsd.getJe());
        hccgjsd.setSe(0 - hccgjsd.getSe());
        hccgjsd.setCe(0 - hccgjsd.getCe());
        hccgjsd.setFpze(0 - hccgjsd.getFpze());

        List<Cgjsdmx> cgjsdmxList = ycgjsd.getCgjsdmxList();
        List<Cgjsdmx> hccgjsdmxList = new ArrayList<Cgjsdmx>();
        for (Cgjsdmx cgjsdmx : cgjsdmxList) {
            Cgjsdmx hccgjsdmx = new Cgjsdmx();
            ReflectionUtils.getInstance(hccgjsdmx, cgjsdmx);
            hccgjsdmx.setId(null);
            hccgjsdmx.setJe(0 - cgjsdmx.getJe());
            hccgjsdmx.setSe(0 - cgjsdmx.getSe());
            hccgjsdmx.setCe(0 - cgjsdmx.getCe());
            hccgjsdmx.setRksl(0 - cgjsdmx.getRksl());
            hccgjsdmx.setJsd(hccgjsd);
            hccgjsdmx.setCreateUser(cgjsdmx.getCreateUser());
            hccgjsdmx.setCreateOrgan(cgjsdmx.getCreateOrgan());
            hccgjsdmx.setCreateDepartment(cgjsdmx.getCreateDepartment());
            hccgjsdmx.setDateCreated(new Date());
            hccgjsdmx.setLastUpdated(hccgjsd.getDateCreated());
            this.cgjsdmxDao.save(hccgjsdmx);
            hccgjsdmxList.add(hccgjsdmx);
        }
        hccgjsd.setCgjsdmxList(hccgjsdmxList);

        List<Zjbcd> zjbcdList = ycgjsd.getZjbcdList();
        List<Zjbcd> hczjbcdList = new ArrayList<Zjbcd>();
        for (Zjbcd zjbcd : zjbcdList) {
            Zjbcd hczjbcd = new Zjbcd();
            ReflectionUtils.getInstance(hczjbcd, zjbcd);
            hczjbcd.setId(null);
            hczjbcd.setJe(0 - zjbcd.getJe());
            hczjbcd.setJsd(hccgjsd);
            hczjbcd.setCreateUser(zjbcd.getCreateUser());
            hczjbcd.setCreateOrgan(zjbcd.getCreateOrgan());
            hczjbcd.setCreateDepartment(zjbcd.getCreateDepartment());
            hczjbcd.setDateCreated(new Date());
            hczjbcd.setLastUpdated(hczjbcd.getDateCreated());
            this.zjbcdDao.save(hczjbcd);
            hczjbcdList.add(hczjbcd);
        }
        hccgjsd.setZjbcdList(hczjbcdList);

        List<Cgdmx> cgdmxList = ycgjsd.getCgdmxList();
        for (int i = 0; i < cgdmxList.size(); i++) {
            Cgdmx cgdmx = cgdmxList.get(i);
            cgdmx.setYjs(false);
            cgdmx.setCgjsd(null);
            this.cgdmxDao.save(cgdmx);

            Cgd cgd = cgdmx.getCgd();
            if (cgd.getYjs()) {
                Boolean flag = false;
                List<Cgdmx> cgmxList = cgdmx.getCgd().getCgdmxList();
                for (Cgdmx cgdmx1 : cgmxList) {
                    if (cgdmx1.getYjs()) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    cgd.setYjs(false);
                    cgd.setCgjsd(null);
                    this.cgdDao.save(cgd);
                }
            }
        }

        hccgjsd.setSftzd(true);
        hccgjsd.setYjsd(ycgjsd);
        hccgjsd.setCgdList(null);
        hccgjsd.setCgdmxList(null);
        hccgjsd.setXsdList(null);
        hccgjsd.setXsdmxList(null);
        hccgjsd.setWldList(null);
        hccgjsd.setXsjsdmxList(null);
        hccgjsd.setWljsdmxList(null);
        hccgjsd.setAcctyear(null);
        hccgjsd.setUuid(null);
        hccgjsd.setVoucherId(null);
        hccgjsd.setVoucherNum(null);
        hccgjsd.setInsertFlag(1);
        hccgjsd.setDeleteFlag(1);
        hccgjsd.setCreateUser(ycgjsd.getCreateUser());
        hccgjsd.setCreateOrgan(ycgjsd.getCreateOrgan());
        hccgjsd.setCreateDepartment(ycgjsd.getCreateDepartment());
        hccgjsd.setDateCreated(new Date());
        hccgjsd.setLastUpdated(hccgjsd.getDateCreated());
        hccgjsd.setSqrq(hccgjsd.getDateCreated());
        hccgjsd.setKprq(hccgjsd.getDateCreated());
        this.cgjsdDao.save(hccgjsd);

        ycgjsd.setCgdList(null);
        ycgjsd.setCgdmxList(null);
        ycgjsd.setXsdList(null);
        ycgjsd.setXsdmxList(null);
        ycgjsd.setWldList(null);
        ycgjsd.setXsjsdmxList(null);
        ycgjsd.setWljsdmxList(null);
        ycgjsd.setSftzd(true);
        ycgjsd.setLastUpdated(new Date());
        this.cgjsdDao.save(ycgjsd);
    }

    /**
     * 关联判断
     *
     * @param cgjsd
     */
    private void nullId(Jsd cgjsd) {
        if (cgjsd != null && cgjsd.getGlqy() != null && cgjsd.getGlqy().getQyfr() != null && cgjsd.getGlqy().getQyfr().getId() == null)
            cgjsd.getGlqy().setQyfr(null);
        if (cgjsd != null && cgjsd.getSqr() != null && cgjsd.getSqr().getId() == null)
            cgjsd.setSqr(null);
        if (cgjsd != null && cgjsd.getGlqy() != null && cgjsd.getGlqy().getId() == null)
            cgjsd.setGlqy(null);
        if (cgjsd != null && cgjsd.getGs() != null && cgjsd.getGs().getId() == null)
            cgjsd.setGs(null);
    }

    @Autowired
    public void setCgjsdDao(CgjsdDao cgjsdDao) {
        this.cgjsdDao = cgjsdDao;
    }

    @Autowired
    public void setCgjsdmxDao(CgjsdmxDao cgjsdmxDao) {
        this.cgjsdmxDao = cgjsdmxDao;
    }

    @Autowired
    public void setCgdmxDao(CgdmxDao cgdmxDao) {
        this.cgdmxDao = cgdmxDao;
    }

    @Autowired
    public void setBmService(BmService bmService) {
        this.bmService = bmService;
    }

    @Autowired
    public void setCgdDao(CgdDao cgdDao) {
        this.cgdDao = cgdDao;
    }

    @Autowired
    public void setZjbcdDao(ZjbcdDao zjbcdDao) {
        this.zjbcdDao = zjbcdDao;
    }

    public String getJsdbm() {
        return bmService.getJsdbm("CGJS");
    }
}
